package com.tz.online.order.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.tz.online.entity.Order;
import com.tz.online.entity.User;
import com.tz.online.order.dao.IOrderDao;
import com.tz.online.util.HibernateCallback;
import com.tz.online.util.HibernateTemplate;

/*****
 * 订单DAO的CRUD操作
 * @author yejf
 *
 */
public class OrderDaoImpl implements IOrderDao {

	private HibernateTemplate template = new HibernateTemplate();
	
	@Override
	public void save(Order o) {
		//
		template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				ses.save(o);
				return null;
			}
		});
	}

	@Override
	public Order findById(Long id) {
		//
		return (Order) template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				return ses.get(Order.class, id);
			}
		});
	}

	@Override
	public void delete(Order o) {
		//
		template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				ses.delete(o);
				return null;
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> selectByPage(User user, int now, int size) {
		//
		return (List<Order>) template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				return ses.createQuery("from Order as o where o.user.id = :id order by o.id")
						.setLong("id", user.getId())
						.setFirstResult((now-1)*size)
						.setMaxResults(size)
						.list();
			}
		});
	}

	@Override
	public int rowCount(User user) {
		Long count = (Long) template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				return ses.createCriteria(Order.class,"o")
						.createAlias("o.user", "u")
						.setProjection(Projections.rowCount())
						.add(Restrictions.eq("u.id", user.getId()))
						.uniqueResult();
			}
		});
		return count.intValue();
	}

}
